package com.yuanluludev.update

import android.app.Activity
import android.content.Context
import com.yuanluludev.lib_base.base.BaseActivity
import com.yuanluludev.lib_utils.util.ActivityUtils
import com.yuanluludev.lib_utils.util.AppUtils
import com.yuanluludev.lib_xpopup.CommonDialogUtils

/**
 * yuanLulu
 * 应用升级
 */
object UpdateManager {

    /**
     * 手动检查更新 默认不显示提示
     */
    fun checkVersionUpdate(
        context: Activity,
        updateInfoBean: UpdateInfoBean? = null,
        isShowTipDialog: Boolean = false,
        isBackgroundDownload: Boolean = false,
    ) {
        updateInfoBean?.apply {
            val currentVersionCode = AppUtils.getAppVersionCode()
            if (currentVersionCode < this.serverVersionCode) {
                //有更新
                showNewVersionDialog(context, this, isBackgroundDownload)
            } else {
                //没有更新
                if (isShowTipDialog) showNoNewVersionDialog(context)
            }
        }
    }

    /**
     * 显示新版本的弹窗
     */
    private fun showNewVersionDialog(
        context: Context,
        model: UpdateInfoBean,
        isBackgroundDownload: Boolean,
    ) {
        if (ActivityUtils.isActivityAlive(context)) {
            UpdateDialog
                .newInstance(model, isBackgroundDownload)
                .show(
                    (context as BaseActivity?)?.supportFragmentManager,
                    isCancelable = false
                )
        }
    }

    /**
     * 显示无新版本的弹窗
     */
    private fun showNoNewVersionDialog(context: Context) {
        if (ActivityUtils.isActivityAlive(context)) {
            CommonDialogUtils.showConfirmDialog(
                context = context,
                content = "当前已是最新版本",
                isHideCancel = true
            )
        }
    }

}